package com.zky.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.zky.domain.constants.RedisConstants;
import com.zky.domain.dto.LoginRequest;
import com.zky.domain.po.Result;
import com.zky.domain.po.User;
import com.zky.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("login")
/**
 * 返回token,userInfo和role
 */
@RequiredArgsConstructor
@Api(tags = "登录相关接口")
public class LoginController {

    private final StringRedisTemplate stringRedisTemplate;
    @ApiOperation("用户登录")
    @PostMapping
    public Result login(@RequestBody LoginRequest loginRequest) throws Exception {
        //检查用户列表
        Set<String> members = stringRedisTemplate.opsForSet().members(RedisConstants.REDIS_USERS_PRE);
        //逐个反序列化
        List<User> userList = new ArrayList<>();
        for (String member : members) {
            userList.add(JSONUtil.toBean(member, User.class));
        }
        //检查有没有对应的用户
        for (User user : userList) {
            if(user.getUserName().equals(loginRequest.getUserName())) {
                if(user.getPassword().equals(loginRequest.getPassword())) {

                    StpUtil.login(loginRequest.getUserName(),10000);
                    //登录后获取token
                    String s =StpUtil.getTokenValue();

                    Object loginId = null;
                    try {
                        loginId = StpUtil.getLoginId();
                    } catch (Exception e) {
                        return Result.fail(e.getMessage());
                    }
                    System.out.println(loginId);
                    //返回token,role,userInfo
                    HashMap<String, String> map = new HashMap<>();
                    map.put("token",s);
                    map.put("userInfo",user.getUserName());
                    map.put("role",user.getRole());
                    return Result.ok(map);

                }
                else {
                    throw new Exception("密码错误");
                }

            }
        }
        throw new Exception("账号错误");


    }
    @GetMapping
    public Result isLogin() {
        return Result.ok(UserUtil.isLogin());
    }
}
